<template>
  <el-dialog v-model="visible" :width="1200" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" destroy-on-close>
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
       <el-row>
         <el-col :span="12">
           <el-form-item label="矿区名" prop="name">
             <el-input v-model="dataForm.name" placeholder="矿区名"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item prop="sysOrgId" label="所属公司" label-width="150">
             <ma-org-select v-model="dataForm.sysOrgId" placeholder="请选择"></ma-org-select>
           </el-form-item>
         </el-col>
       </el-row>
      <!--			<el-form-item label="位置" prop="address">-->
      <!--				<el-input v-model="dataForm.address" placeholder="位置"></el-input>-->
      <!--			</el-form-item>-->
      <!-- <el-form-item label="经度" prop="longitude">
				<el-input v-model="dataForm.longitude" placeholder="经度"></el-input>
			</el-form-item>
			<el-form-item label="纬度" prop="latitude">
				<el-input v-model="dataForm.latitude" placeholder="纬度"></el-input>
			</el-form-item> -->
      <el-form-item label="画线">
        <el-radio-group v-model="drawType" :disabled="isDrawing" @change="drawTypeChange(0)">
          <!-- <el-radio :value="0">矿区位置</el-radio> -->
          <el-radio :value="1">起点围栏</el-radio>
          <el-radio :value="2">起点装货围栏</el-radio>
          <el-radio :value="3">运输线路</el-radio>
          <el-radio :value="4">终点围栏</el-radio>
          <el-radio :value="5">终点卸货围栏</el-radio>
        </el-radio-group>
        <el-button type="primary" size="default" @click="startDraw">{{ !isDrawing ? '开始画围栏' : '结束画围栏' }}</el-button>
        <el-button type="primary" size="default" :disabled="!isDrawing" @click="clearDraw">清除重画</el-button>
        <el-button v-if="drawType >= 4 && !isDrawing" type="primary" size="default" @click="useSaved">使用国能新疆公司围栏</el-button>
      </el-form-item>
      <!-- <el-form-item label="起点围栏" prop="fenceStart">
				<el-radio-group v-model="dataForm.fenceStart">
					<el-radio :label="0">起点围栏</el-radio>
					<el-radio :label="1">终点围栏</el-radio>
					<el-radio :label="2">运输线路</el-radio>
				</el-radio-group>
			</el-form-item> -->
      <!-- <el-form-item label="运输线路" prop="line">
				<el-input v-model="dataForm.line" placeholder="运输线路"></el-input>
			</el-form-item>
			<el-form-item label="终点围栏" prop="fenceEnd">
				<el-input v-model="dataForm.fenceEnd" placeholder="终点围栏"></el-input>
			</el-form-item> -->
    </el-form>
    <div id="map-fence" class="map-fence"></div>
    <template #footer>
      <el-button :disabled="isDrawing" @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="isDrawing" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useMineApi, useMineSubmitApi, savedFence } from '@/api/biz/mine'
import 'ol/ol.css'
import { Feature, Map } from 'ol'
import { Vector as LayerVector } from 'ol/layer'
// import SourceVector from 'ol/source/Vector'
// import StyleVector from 'ol/style/Style'
import layerVecor from 'ol/layer/Vector'
import { Vector as SourceVector } from 'ol/source' // Stamen是底图
import { Circle as StyleCircle, Fill, Icon, Stroke, Style, Style as StyleVector } from 'ol/style'
import { Polygon, Circle as GeomCircle, LineString, Point } from 'ol/geom'
import { Draw, Modify, Snap } from 'ol/interaction'
import { transform } from 'ol/proj'
import { wsg2mapcoor } from '@/utils/gps/maptransform'
import { fenceDecode, fenceEncode, getCenterPoint, getCenterPoint1 } from '@/utils/gps/fence'
import { createLayers2, createMap } from '@/utils/ol/maptools'

// const startImg: any = require("@/assets/gps/start_icon.png") //轨迹起点图标
// const endImg: any = require("@/assets/gps/end_icon.png") //轨迹终点图标
import posIcon from '@/assets/gps/pos_icon.png'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
  id: '',
  name: '',
  longitude: 0,
  latitude: 0,
  fenceStart: '',
  fenceStart2: '',
  line: '',
  fenceEnd: '',
  fenceEnd2: '',
  sysOrgId: ''
})
const savedFenceStr = ref(['', ''])

const init = (id?: number) => {
  visible.value = true
  dataForm.id = ''
  dataForm.name = ''
  dataForm.longitude = 0
  dataForm.latitude = 0
  dataForm.fenceStart = ''
  dataForm.fenceStart2 = ''
  dataForm.line = ''
  dataForm.fenceEnd = ''
  dataForm.fenceEnd2 = ''
  // 重置表单数据
  // if (dataFormRef.value) {
  //   dataFormRef.value.resetFields()
  // }
  clearMap()
  drawType.value = 1
  savedFence()
    .then((res: any) => {
      savedFenceStr.value = res.data
    })
    .finally(() => {
      if (id) {
        getMine(id)
      } else {
        dataForm.fenceEnd = savedFenceStr.value[0]
        dataForm.fenceEnd2 = savedFenceStr.value[1]
        initMap0()
      }
    })
}

const getMine = (id: number) => {
  useMineApi(id).then((res) => {
    Object.assign(dataForm, res.data)
    initMap0()
  })
}

const dataRules = reactive<FormRules>({
  name: { required: true, message: '请输入矿区名', trigger: 'blur' },
  longitude: { required: true, message: '', trigger: 'blur' },
  latitude: { required: true, message: '', trigger: 'blur' },
  fenceStart: { required: true, message: '', trigger: 'blur' },
  line: { required: true, message: '', trigger: 'blur' },
  fenceEnd: { required: true, message: '', trigger: 'blur' },
  sysOrgId: { required: true, message: '请选择公司', trigger: 'blur' }
})

// 表单提交
const submitHandle = () => {
  console.log(dataFormRef.value)
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    useMineSubmitApi(dataForm).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
        }
      })
    })
  })
}

defineExpose({
  init
})

let openMap: Map
let source: any = new SourceVector()
let layers = [] as any
let center: any = null
const drawType = ref(1)
const isDrawing = ref(false)

let minePosLayer: any = null
let layer1: any = null
let layer12: any = null
let layer2: any = null
let layer22: any = null
let layer3: any = null
let drawingLayer: any = null

let drawing: any = null
let modifing: any = null
let snaping: any = null

let circleInfo: any = null
let polygonPath: any = [] //mapcoor
let linePath: any = []
const seFenceIsCircle = ref(false)

const initMap0 = () => {
  layers = createLayers2()
  nextTick(() => {
    initMap()
  })
}
const clearMap = () => {
  if (source) {
    source.clear()
  }
  if (minePosLayer) {
    openMap.removeLayer(minePosLayer)
    minePosLayer = null
  }
  if (layer2) {
    openMap.removeLayer(layer2)
    layer2 = null
  }
  if (layer3) {
    openMap.removeLayer(layer3)
    layer3 = null
  }
}
const initMap = () => {
  openMap = createMap('map-fence', layers, center ? [center.lng, center.lat] : undefined)
  draw()
  drawTypeChange(1)
}
const animateTo = (longitude: number, latitude: number) => {
  // 设置地图中心
  let mapView = openMap.getView()
  // mapView.setCenter([endPos.lng, endPos.lat])
  mapView.animate({
    center: [longitude, latitude],
    duration: 500
    // zoom: 12
  })
}
const draw = () => {
  if (dataForm.latitude && dataForm.longitude) {
    let minePos = wsg2mapcoor(dataForm.longitude, dataForm.latitude)
    if (minePosLayer) {
      openMap.removeLayer(minePosLayer)
    }
    minePosLayer = createPointLayer(minePos.lng, minePos.lat, posIcon)
    openMap.addLayer(minePosLayer)
  }
  if (dataForm.fenceStart) {
    if (layer1) {
      openMap.removeLayer(layer1)
    }
    const area: any = fenceDecode(dataForm.fenceStart)
    if (seFenceIsCircle.value) {
      let center = [area.path[0].lng, area.path[0].lat]
      let radius = Number(area.path[1])
      layer1 = createLayer1(center, radius)
    } else {
      // 多边形坐标点
      let gpsPath: any = []
      // this.center = this.getCenterPoint(area.path)
      area.path.map((e: any) => {
        gpsPath.push([e.lng, e.lat])
      })
      layer1 = createLayer2(gpsPath, true)
    }
    if (!(drawType.value === 2 && isDrawing.value)) {
      openMap.addLayer(layer1)
    }
  }
  if (dataForm.fenceStart2) {
    if (layer12) {
      openMap.removeLayer(layer12)
    }
    const area: any = fenceDecode(dataForm.fenceStart2)
    if (seFenceIsCircle.value) {
      let center = [area.path[0].lng, area.path[0].lat]
      let radius = Number(area.path[1])
      layer12 = createLayer1(center, radius)
    } else {
      // 多边形坐标点
      let gpsPath: any = []
      // this.center = this.getCenterPoint(area.path)
      area.path.map((e: any) => {
        gpsPath.push([e.lng, e.lat])
      })
      layer12 = createLayer2(gpsPath, true)
    }
    openMap.addLayer(layer12)
  }
  if (dataForm.fenceEnd) {
    if (layer2) {
      openMap.removeLayer(layer2)
    }
    const area: any = fenceDecode(dataForm.fenceEnd)
    if (seFenceIsCircle.value) {
      let center = [area.path[0].lng, area.path[0].lat]
      let radius = Number(area.path[1])
      layer2 = createLayer1(center, radius)
    } else {
      let gpsPath: any = []
      area.path.map((e: any) => {
        gpsPath.push([e.lng, e.lat])
      })
      layer2 = createLayer2(gpsPath, false)
    }
    if (!(drawType.value === 5 && isDrawing.value)) {
      openMap.addLayer(layer2)
    }
  }
  if (dataForm.fenceEnd2) {
    if (layer22) {
      openMap.removeLayer(layer22)
    }
    const area: any = fenceDecode(dataForm.fenceEnd2)
    if (seFenceIsCircle.value) {
      let center = [area.path[0].lng, area.path[0].lat]
      let radius = Number(area.path[1])
      layer22 = createLayer1(center, radius)
    } else {
      // 多边形坐标点
      let gpsPath: any = []
      // this.center = this.getCenterPoint(area.path)
      area.path.map((e: any) => {
        gpsPath.push([e.lng, e.lat])
      })
      layer22 = createLayer2(gpsPath, false)
    }
    openMap.addLayer(layer22)
  }
  if (dataForm.line) {
    if (layer3) {
      openMap.removeLayer(layer3)
    }
    const area: any = fenceDecode(dataForm.line)
    let gpsPath: any = []
    area.path.map((e: any) => {
      gpsPath.push([e.lng, e.lat])
    })
    layer3 = createLayer3(gpsPath)
    openMap.addLayer(layer3)
  }
}

const createPointLayer = (lng: number, lat: number, icon: any) => {
  let iconFeature = new Feature({
    geometry: new Point([lng, lat])
  })
  // 创建图标样式
  let iconStyle = new Style({
    image: new Icon({
      // 定义图标锚点
      anchor: [24, 0],
      anchorOrigin: 'bottom-left',
      anchorXUnits: 'pixels',
      anchorYUnits: 'pixels',
      src: icon,
      width: 48,
      height: 48,
      size: [48, 48]
    })
  })
  // 样式加载到图标
  iconFeature.setStyle(iconStyle)
  // 图标添加进矢量容器
  let vectorSource = new SourceVector({
    features: [iconFeature]
  })
  // 创建矢量图层
  return new layerVecor({
    source: vectorSource
  })
}
const createLayer1 = (center: any, radius: number) => {
  // 转化（以为米画圆）
  let circleIn3857 = new GeomCircle(transform(center, 'EPSG:4326', 'EPSG:3857'), radius, 'XY')
  let circleIn4326 = circleIn3857.transform('EPSG:3857', 'EPSG:4326')
  const circle = new Feature(circleIn4326)
  // 创建一个中心为[0, 0]，半径为1的圆形
  // const circle = new Feature(new GeomCircle([0, 0], 1))
  // 配置样式
  circle.setStyle(
    new StyleVector({
      stroke: new Stroke({
        color: '#AACC33',
        width: 5
      })
    })
  )
  const source = new SourceVector()
  // 把圆形添加到 source 中
  source.addFeature(circle)
  return new LayerVector({
    source: source
  })
}
const createLayer2 = (gpsPath: any, start: boolean) => {
  // 在包一层
  const polygon = new Feature(new Polygon([gpsPath]))
  // const polygon = new Feature({ geometry: new Polygon([gpsPath]) })
  // 配置样式
  if (start) {
    polygon.setStyle(
      new StyleVector({
        stroke: new Stroke({
          color: '#3333ff',
          width: 5
        }),
        fill: new Fill({
          color: 'rgba(51, 51, 255, 0.5)'
        })
      })
    )
  } else {
    polygon.setStyle(
      new StyleVector({
        stroke: new Stroke({
          color: '#00cc00',
          width: 5
        }),
        fill: new Fill({
          color: 'rgba(0, 204, 0, 0.5)'
        })
      })
    )
  }
  const source = new SourceVector()
  source.addFeature(polygon)
  return new LayerVector({
    source: source
  })
}
const createLayer3 = (gpsPath: any) => {
  const line = new Feature({
    geometry: new LineString(gpsPath)
  })
  console.log(gpsPath, line)
  // 配置样式
  line.setStyle(
    new Style({
      stroke: new Stroke({
        color: '#ee0000',
        width: 3
      })
    })
  )
  const source = new SourceVector()
  // 添加线到 source
  source.addFeature(line)
  return new LayerVector({
    source: source
  })
}
const createDrawingLayer = (source1: any) => {
  // 样式
  return new LayerVector({
    source: source1,
    style: new Style({
      fill: new Fill({
        color: 'rgba(49,173,252, 0.2)'
      }),
      stroke: new Stroke({
        color: '#0099FF',
        width: 3
      }),
      image: new StyleCircle({
        radius: 7,
        fill: new Fill({
          color: '#0099FF'
        })
      })
    })
  })
}
const drawTypeChange = (pid: any) => {
  // console.log(drawType.value)
  switch (drawType.value) {
    case 0:
      break
    case 1:
      if (dataForm.fenceStart) {
        const area: any = fenceDecode(dataForm.fenceStart) // map
        if (area.type === 'CIRCLE') {
        } else if (area.type === 'POLYGON') {
          let center = getCenterPoint(area.path)
          animateTo(center.lng, center.lat)
        }
      }
      break
    case 2:
      if (dataForm.fenceStart2) {
        const area: any = fenceDecode(dataForm.fenceStart2) // map
        if (area.type === 'CIRCLE') {
        } else if (area.type === 'POLYGON') {
          let center = getCenterPoint(area.path)
          animateTo(center.lng, center.lat)
        }
      }
      break
    case 3:
      if (dataForm.line) {
        const area: any = fenceDecode(dataForm.line)
        if (area.type === 'LINESTRING') {
          let center = getCenterPoint(area.path)
          // animateTo(center.lng, center.lat)
        }
      }
      break
    case 4:
      if (dataForm.fenceEnd) {
        const area: any = fenceDecode(dataForm.fenceEnd)
        if (area.type === 'CIRCLE') {
        } else if (area.type === 'POLYGON') {
          let center = getCenterPoint(area.path)
          animateTo(center.lng, center.lat)
        }
      }
      break
    case 5:
      if (dataForm.fenceEnd2) {
        const area: any = fenceDecode(dataForm.fenceEnd2)
        if (area.type === 'CIRCLE') {
        } else if (area.type === 'POLYGON') {
          let center = getCenterPoint(area.path)
          animateTo(center.lng, center.lat)
        }
      }
      break
  }
}

function mineClick(event) {
  let pixel = openMap!.getEventPixel(event.originalEvent)
  const coordinate = event.coordinate
  dataForm.longitude = coordinate[0]
  dataForm.latitude = coordinate[1]
  draw()
}
const startDraw = () => {
  if (!isDrawing.value) {
    isDrawing.value = true
    draw()
    let feature: any = null
    switch (drawType.value) {
      case 0:
        openMap.on('click', mineClick)
        break
      case 1:
        if (dataForm.fenceStart) {
          if (layer1) {
            openMap.removeLayer(layer1)
            layer1 = null
          }
          const area: any = fenceDecode(dataForm.fenceStart)
          if (seFenceIsCircle.value) {
            let center = [area.path[0].lng, area.path[0].lat]
            let radius = Number(area.path[1])
            circleInfo = {
              center,
              radius
            }
            let circleIn3857 = new GeomCircle(transform(center, 'EPSG:4326', 'EPSG:3857'), radius, 'XY')
            let circleIn4326 = circleIn3857.transform('EPSG:3857', 'EPSG:4326')
            feature = new Feature(circleIn4326)
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Circle')
          } else {
            // 多边形坐标点
            let gpsPath: any = []
            // this.center = this.getCenterPoint(area.path)
            area.path.map((e: any) => {
              gpsPath.push([e.lng, e.lat])
            })
            polygonPath = gpsPath
            feature = new Feature(new Polygon([gpsPath]))
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Polygon')
          }
        } else {
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          if (seFenceIsCircle.value) {
            addInteractions('Circle')
          } else {
            addInteractions('Polygon')
          }
        }
        break
      case 2:
        if (dataForm.fenceStart2) {
          if (layer12) {
            openMap.removeLayer(layer12)
            layer12 = null
          }
          const area: any = fenceDecode(dataForm.fenceStart2)
          if (seFenceIsCircle.value) {
            let center = [area.path[0].lng, area.path[0].lat]
            let radius = Number(area.path[1])
            circleInfo = {
              center,
              radius
            }
            let circleIn3857 = new GeomCircle(transform(center, 'EPSG:4326', 'EPSG:3857'), radius, 'XY')
            let circleIn4326 = circleIn3857.transform('EPSG:3857', 'EPSG:4326')
            feature = new Feature(circleIn4326)
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Circle')
          } else {
            // 多边形坐标点
            let gpsPath: any = []
            // this.center = this.getCenterPoint(area.path)
            area.path.map((e: any) => {
              gpsPath.push([e.lng, e.lat])
            })
            polygonPath = gpsPath
            feature = new Feature(new Polygon([gpsPath]))
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Polygon')
          }
        } else {
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          if (seFenceIsCircle.value) {
            addInteractions('Circle')
          } else {
            addInteractions('Polygon')
          }
        }
        break
      case 3:
        if (dataForm.line) {
          if (layer3) {
            openMap.removeLayer(layer3)
            layer3 = null
          }
          const area: any = fenceDecode(dataForm.line)
          let gpsPath: any = []
          area.path.map((e: any) => {
            gpsPath.push([e.lng, e.lat])
          })
          linePath = gpsPath
          feature = new Feature(new LineString(gpsPath))
          source = new SourceVector({
            features: [feature]
          })
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          editInteractions('LineString')
        } else {
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          addInteractions('LineString')
        }
        break
      case 4:
        if (dataForm.fenceEnd) {
          if (layer2) {
            openMap.removeLayer(layer2)
            layer2 = null
          }
          const area: any = fenceDecode(dataForm.fenceEnd) //mapcoor
          if (seFenceIsCircle.value) {
            let center = [area.path[0].lng, area.path[0].lat]
            let radius = Number(area.path[1])
            circleInfo = {
              center,
              radius
            }
            let circleIn3857 = new GeomCircle(transform(center, 'EPSG:4326', 'EPSG:3857'), radius, 'XY')
            let circleIn4326 = circleIn3857.transform('EPSG:3857', 'EPSG:4326')
            feature = new Feature(circleIn4326)
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Circle')
          } else {
            // 多边形坐标点
            let gpsPath: any = []
            area.path.map((e: any) => {
              gpsPath.push([e.lng, e.lat])
            })
            polygonPath = gpsPath
            feature = new Feature(new Polygon([gpsPath]))
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Polygon')
          }
        } else {
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          if (seFenceIsCircle.value) {
            addInteractions('Circle')
          } else {
            addInteractions('Polygon')
          }
        }
        break
      case 5:
        if (dataForm.fenceEnd2) {
          if (layer22) {
            openMap.removeLayer(layer22)
            layer22 = null
          }
          const area: any = fenceDecode(dataForm.fenceEnd2) //mapcoor
          if (seFenceIsCircle.value) {
            let center = [area.path[0].lng, area.path[0].lat]
            let radius = Number(area.path[1])
            circleInfo = {
              center,
              radius
            }
            let circleIn3857 = new GeomCircle(transform(center, 'EPSG:4326', 'EPSG:3857'), radius, 'XY')
            let circleIn4326 = circleIn3857.transform('EPSG:3857', 'EPSG:4326')
            feature = new Feature(circleIn4326)
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Circle')
          } else {
            // 多边形坐标点
            let gpsPath: any = []
            area.path.map((e: any) => {
              gpsPath.push([e.lng, e.lat])
            })
            polygonPath = gpsPath
            feature = new Feature(new Polygon([gpsPath]))
            source = new SourceVector({
              features: [feature]
            })
            drawingLayer = createDrawingLayer(source)
            openMap.addLayer(drawingLayer)
            editInteractions('Polygon')
          }
        } else {
          drawingLayer = createDrawingLayer(source)
          openMap.addLayer(drawingLayer)
          if (seFenceIsCircle.value) {
            addInteractions('Circle')
          } else {
            addInteractions('Polygon')
          }
        }
        break
    }
  } else {
    isDrawing.value = false
    draw()
    if (drawing !== null) {
      openMap.removeInteraction(drawing)
      drawing = null
    }
    if (snaping !== null) {
      openMap.removeInteraction(snaping)
      snaping = null
    }
    source.clear()
    if (drawingLayer) {
      openMap.removeLayer(drawingLayer)
      drawingLayer = null
    }
    let code
    console.log(openMap)
    switch (drawType.value) {
      case 0:
        openMap.un('click', mineClick)
        break
      case 1:
        if (seFenceIsCircle.value) {
          code = fenceEncode('Circle', circleInfo, polygonPath, linePath) //wsg
        } else {
          code = fenceEncode('Polygon', circleInfo, polygonPath, linePath)
          let center = getCenterPoint1(polygonPath)
          // console.log(center)
          dataForm.longitude = center.lng
          dataForm.latitude = center.lat
        }
        dataForm.fenceStart = code
        break
      case 2:
        if (seFenceIsCircle.value) {
          code = fenceEncode('Circle', circleInfo, polygonPath, linePath) //wsg
        } else {
          code = fenceEncode('Polygon', circleInfo, polygonPath, linePath)
        }
        dataForm.fenceStart2 = code
        break
      case 3:
        code = fenceEncode('LineString', circleInfo, polygonPath, linePath)
        dataForm.line = code
        break
      case 4:
        if (seFenceIsCircle.value) {
          code = fenceEncode('Circle', circleInfo, polygonPath, linePath)
        } else {
          code = fenceEncode('Polygon', circleInfo, polygonPath, linePath)
        }
        dataForm.fenceEnd = code
        break
      case 5:
        if (seFenceIsCircle.value) {
          code = fenceEncode('Circle', circleInfo, polygonPath, linePath)
        } else {
          code = fenceEncode('Polygon', circleInfo, polygonPath, linePath)
        }
        dataForm.fenceEnd2 = code
        break
    }
    draw()
  }
}
const clearDraw = () => {
  if (isDrawing.value) {
    if (modifing !== null) {
      openMap.removeInteraction(modifing)
    }
    source.clear()
    switch (drawType.value) {
      case 0:
        openMap!.un('click', (event) => {})
        break
      case 1:
        if (seFenceIsCircle.value) {
          addInteractions('Circle')
        } else {
          addInteractions('Polygon')
        }
        break
      case 2:
        if (seFenceIsCircle.value) {
          addInteractions('Circle')
        } else {
          addInteractions('Polygon')
        }
        break
      case 3:
        addInteractions('LineString')
        break
    }
  }
}
const useSaved = () => {
  dataForm.fenceEnd = savedFenceStr.value[0]
  dataForm.fenceEnd2 = savedFenceStr.value[1]
  draw()
  drawTypeChange(0)
}
// 绘制图形
const addInteractions = (tool: string) => {
  if (drawing !== null) {
    openMap.removeInteraction(drawing)
  }
  if (snaping !== null) {
    openMap.removeInteraction(snaping)
  }
  // 绘制几何
  drawing = new Draw({ source: source, type: tool as any })
  openMap.addInteraction(drawing)
  // 加入光标捕捉
  snaping = new Snap({ source: source })
  openMap.addInteraction(snaping)
  drawing.on('drawend', (e: any) => {
    // 绘制完成的回调
    drawingEnd(e)
    if (drawing !== null) {
      openMap.removeInteraction(drawing)
    }
    if (snaping !== null) {
      openMap.removeInteraction(snaping)
    }
    editInteractions(tool)
  })
  drawing.on('drawstart', () => {
    if (tool === 'Circle') {
      if (circleInfo) {
        source.clear()
        circleInfo = null
      }
    } else if (tool === 'Polygon') {
      // 如果已经存在则删除上一个几何
      if (polygonPath) {
        source.clear()
        polygonPath = []
      }
    } else if (tool === 'LineString') {
      if (linePath) {
        source.clear()
        linePath = []
      }
    } else {
    }
  })
}
const editInteractions = (tool: string) => {
  if (modifing !== null) {
    openMap.removeInteraction(modifing)
  }
  // 修改几何
  modifing = new Modify({
    source: source,
    insertVertexCondition: () => true // 如果返回true，可以增加节点
  })
  openMap.addInteraction(modifing)
  // 监听修改
  modifing.on('modifyend', (e: any) => {
    // 修改完成回调参数
    // 因为修改参数格式不一样（需要转换）
    let query = {
      feature: e.features.array_[0]
    }
    // 解析结构
    drawingEnd(query)
  })
  // addInteractions(tool)
}
// 绘制完成解析结构
const drawingEnd = (evt: any) => {
  let geo = evt.feature.getGeometry()
  let type = geo.getType() //获取类型
  if (type === 'Circle') {
    // 转换坐标
    let circleIn3857 = new GeomCircle(transform(geo.getCenter(), 'EPSG:3857', 'EPSG:4326'), geo.getRadius(), 'XY')
    let circleIn4326 = circleIn3857.transform('EPSG:4326', 'EPSG:3857')
    //获取中心点和半径
    let center = circleIn4326.getCenter()
    let radius = circleIn4326.getRadius()
    circleInfo = {
      center: center,
      radius: parseInt(radius + '')
    }
  } else if (type === 'Polygon') {
    //获取坐标点
    let points = geo.getCoordinates()
    polygonPath = points[0]
  } else if (type === 'LineString') {
    //获取坐标点
    // console.log(points)
    linePath = geo.getCoordinates()
  } else {
  }
}
</script>

<style lang="scss">
.map-fence {
  width: 100%;
  height: 60vh;
  background-color: #008080;
}
.cr-address .el-input-group__append {
  background-color: #008080;
  color: #fff;
}
.cr-address-box {
  position: relative;
}
.cr-po {
  position: absolute;
  z-index: 9999;
  top: 37px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgb(207, 207, 207);
  left: 0px;
  right: 0px;
  height: 0px;
  overflow: hidden;
  background-color: #ffffff;
  transition: height 0.3s linear;
}
.cr-po-show {
  height: 130px;
  overflow: scroll;
  overflow-x: hidden;
  cursor: pointer;
  div {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 0 15px;
    font-size: 14px;
    color: rgb(27, 27, 27);
  }
  div:hover {
    background-color: rgb(238, 238, 238);
  }
}
</style>
